package com.lmwyc.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class HttpUtil {

	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	/**
	 * 模拟请求
	 * 
	 * @param url
	 *            资源地址
	 * @param map
	 *            参数列表
	 * @param encoding
	 *            编码
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static String sendPost(String url, Map<String, String> map, String encoding, String sessionId) {
		String body = "";

		// 创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		// 创建post方式请求对象
		HttpPost httpPost = new HttpPost(url);

		// 装填参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (map != null) {
			for (Entry<String, String> entry : map.entrySet()) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		CloseableHttpResponse response = null;
		try {
			// 设置参数到请求对象中
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

			logger.info("请求地址：" + url);
			logger.info("请求参数：" + nvps.toString());

			// 设置header信息
			// 指定报文头【Content-type】、【User-Agent】
			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpPost.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 4.4.2; SM-G955N Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36 MicroMessenger/6.6.7.1321(0x26060736) NetType/WIFI Language/zh_CN");
			httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);
			// 执行请求操作，并拿到结果（同步阻塞）
			response = client.execute(httpPost);
			// 获取结果实体
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				// 按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, encoding);
			}
			EntityUtils.consume(entity);
			// 释放链接
		} catch (UnsupportedEncodingException e) {
			logger.error("httppost发送异常：" + e.getMessage());
		} catch (ClientProtocolException e) {
			logger.error("httppost发送异常：" + e.getMessage());
		} catch (org.apache.http.ParseException e) {
			logger.error("httppost发送异常：" + e.getMessage());
		} catch (IOException e) {
			logger.error("httppost发送异常：" + e.getMessage());
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error("httppost发送异常：" + e.getMessage());
				}
			}
		}
		return body;
	}

	public static String sendGet(String targetURL, Map<String, String> paramMap, String encoding, String sessionId) {
		String body = "";
		// 创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		// 创建post方式请求对象
		HttpGet httpGet = new HttpGet(targetURL);
		CloseableHttpResponse response = null;
		try {
			if (targetURL.indexOf("?") == -1) {
				targetURL += "?";
			}
			targetURL += uriMapToString(paramMap);

			// 设置header信息
			// 指定报文头【Content-type】、【User-Agent】
			httpGet.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpGet.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 4.4.2; SM-G955N Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36 MicroMessenger/6.6.7.1321(0x26060736) NetType/WIFI Language/zh_CN");
			httpGet.setHeader("Cookie", "JSESSIONID=" + sessionId);

			// 执行请求操作，并拿到结果（同步阻塞）
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				// 按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, encoding);
			}
			EntityUtils.consume(entity);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("httpGet发送异常：" + e.getMessage());
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return body;
	}

	private static String uriMapToString(Map<String, String> paramMap) {
		if(paramMap == null){
			return "";
		}
		Set<String> set = paramMap.keySet();
		StringBuffer postedData = new StringBuffer();
		for (Iterator<String> it = set.iterator(); it.hasNext();) {
			String key = it.next();
			String value = paramMap.get(key);
			postedData.append(key);
			postedData.append("=");
			try {
				postedData.append(URLEncoder.encode(value, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			postedData.append("&");
		}
		if (postedData.length() > 0) {
			postedData.deleteCharAt(postedData.length() - 1);// 删除末尾分隔符
		}
		return postedData.toString();
	}
}
